package cn.dong.gateway.config;

import cn.dong.api.utils.JwtUtils;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 网关过滤器
 */
@Component
public class GatewayFilterConfig implements Ordered, GlobalFilter {


    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 过滤器
     * Process the Web request and (optionally) delegate to the next {@code WebFilter}
     * through the given {@link GatewayFilterChain}.
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request processing is complete
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取路径
        String path = request.getURI().getPath();
        // 路径中带有auth的路径进行鉴权
        if (antPathMatcher.match("/api/**/auth/**", path)) {
            // 获取请求头的token
            List<String> list = request.getHeaders().get("token");
            // 非空判断
            if (list == null) {
                // 辅助方法返回错误
                return out(response);
            }
            // 获取token
            if (list.get(0) == null) {
                // 辅助方法返回错误
                return out(response);
            }
            // 校验jwt token
            if (!JwtUtils.checkJwtTToken(list.get(0))) {
                // 辅助方法返回错误
                return out(response);
            }
        }

        // 放行
        return chain.filter(exchange);
    }

    /**
     * 过滤器优先级，越小优先级越高
     * Get the order value of this object.
     * <p>Higher values are interpreted as lower priority. As a consequence,
     * the object with the lowest value has the highest priority (somewhat
     * analogous to Servlet {@code load-on-startup} values).
     * <p>Same order values will result in arbitrary sort positions for the
     * affected objects.
     *
     * @return the order value
     * @see #HIGHEST_PRECEDENCE
     * @see #LOWEST_PRECEDENCE
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 过滤器辅助方法
     * @param response
     * @return
     */
    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("code", 28004);
        message.addProperty("data", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        // response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
